package com.situ.blog.dao.impl;

import com.situ.blog.dao.IAuthDao;
import com.situ.blog.pojo.entity.Auth;
import com.situ.blog.pojo.query.AuthQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class AuthDaoImpl implements IAuthDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Auth> selectByPage(AuthQuery authQuery) {
        String sql = "select * from auth where 1=1";

        List<Object> queryList = new ArrayList<>();

        String queryName = authQuery.getName();
        if (queryName != null && !queryName.equals("")){
            sql += " and name like ?";
            queryList.add("%" + queryName + "%");
        }
        sql += " limit ?,?";
        int offset = (authQuery.getPage() - 1)*authQuery.getLimit();
        queryList.add(offset);
        queryList.add(authQuery.getLimit());

        List<Auth> list = template.query(sql,
                new BeanPropertyRowMapper<>(Auth.class),
                queryList.toArray());

        return list;
    }

    @Override
    public List<Auth> selectByRole(Integer role) {
        return template.query("select * from auth where role=?",
                new BeanPropertyRowMapper<>(Auth.class),role);
    }

    @Override
    public int selectTotal(AuthQuery authQuery) {
        String sql = "select count(*) from auth where 1=1";

        List<Object> queryList = new ArrayList<>();
        String queryName = authQuery.getName();
        if (queryName != null && !queryName.equals("")){
            sql += " and name like ?";
            queryList.add("%"+ queryName +"%");
        }

        return template.queryForObject(sql,Integer.class,queryList.toArray());
    }

    @Override
    public void deleteById(int id) {
        template.update("delete from auth where id=?",id);
    }

    @Override
    public void add(Auth auth) {
        template.update("insert into auth(name) values(?)",auth.getName());
    }

    @Override
    public Auth selectById(int id) {
        return template.queryForObject("select * from auth where id=?",
                new BeanPropertyRowMapper<>(Auth.class),id);
    }

    @Override
    public void update(Auth auth) {
        template.update("update auth set name=? where id=?",auth.getName(),auth.getId());
    }
}
